package src.leetcode.backtrack.medium_0090;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class subsetsWithDup {
    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.subsetsWithDup(new int[]{1, 2, 2}));
    }
}

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path;
    int[] nums;

//    boolean[] used;

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        path = new ArrayList<>(nums.length);
        res.add(path);
        this.nums = nums;
        Arrays.sort(nums);
//        used = new boolean[nums.length];
        int index = 0;
        dfs(index);
        return res;
    }

    private void dfs(int index) {

        if (index == nums.length) {
            return;
        }

        for (int i = index; i < nums.length; i++) {
            while (i > index && i < nums.length && nums[i] == nums[i - 1]) i++;
            if(i == nums.length)
                break;
            path.add(nums[i]);
            res.add(new ArrayList<>(path));
            dfs(i + 1);
            path.remove(path.size() - 1);
        }

    }
}
